package su.msk.jet.team01.chatik.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.SocketException;

public class ClientInputHandler implements Runnable {
	private final ObjectInputStream inStream;
	private final NetworkClient client;

	private static Logger logger = LoggerFactory.getLogger(ClientInputHandler.class);

	public ClientInputHandler(final InputStream is, final NetworkClient client)
			throws IOException {
		inStream = new ObjectInputStream(is);
		this.client = client;
	}

	public void close() throws IOException {
		inStream.close();
	}

	@Override
	public void run() {
		CommandProcessor commandProcessor = CommandProcessor.get();
		String msg;
		
		try {
			while (true) {
				msg = (String) inStream.readObject();
				commandProcessor.process(client.getClient(), msg);
			}
		} catch (EOFException e) {
			logger.info("Client " + client.getClient().getName() + " (" + client.getIP() + ") disconnected.");
		} catch (SocketException e) {
			logger.info("Client " + client.getClient().getName() + " (" + client.getIP() + ") disconnected.");
		} catch (IOException e) {
			logger.warn(e.getMessage());
		} catch (ClassNotFoundException e) {
			logger.warn("Client (" + client.getIP() + ") with invalid version tried to connect, abandoned.");
		} finally {
			client.close();
		}
	}
}
